require 'active_record'

module Named #:nodoc:
  module URL #:nodoc:

    def self.included(mod)
      mod.extend(ClassMethods)
    end

    module ClassMethods
      def named_url(options = {})

        options.assert_valid_keys(:key, :url_column)

        class_eval do
          extend Base::Resource::SingletonMethods
        end

        include Base::Resource::InstanceMethods


        unless options[:key].nil? || options[:url_column].nil?
          module_eval <<-"end_eval", __FILE__, __LINE__

          validates_uniqueness_of :#{options[:url_column]}, :message => "needs to be unique, try changing the title."

          before_validation :make_#{options[:url_column]}

          def to_param
            self.#{options[:url_column]} || id
          end

          def self.find(*args)
            if args.first.is_a?(String)
              find_by_#{options[:url_column]}(args.first.to_s)
            else
              super
            end
          end

          protected
          def make_#{options[:url_column]}
            self.#{options[:url_column]} = self.to_s.gsub(/[^a-z0-9]+/i, '_').downcase
          end
          end_eval
        end

        unless options[:key].nil?
          module_eval <<-"end_eval", __FILE__, __LINE__
          
          validates_presence_of :#{options[:key]}
          
          def to_s
            self.#{options[:key]}
          end
          end_eval
        end
      end
    end

    module SingletonMethods
    end

    # Adds instance methods.
    module InstanceMethods
    end
  end
end


# reopen ActiveRecord and include all the above to make
# them available to all our models if they want it

ActiveRecord::Base.class_eval do
  include Base::Resource
end